<template>
	<view class="uni-pages" @touchmove.stop.prevent="stopRoll" style="position: fixed;top: -10000px;z-index:99999">
		<!-- 海报 -->
		<canvas class="f__canvas" style="width:600px;height:840px"  canvas-id="firstCanvas" id="firstCanvas"></canvas>
		<!-- 生成二维码 -->
		<canvas class="f__canvas" style="width:300px;height:300px;" canvas-id="qrcode" id="qrcode"></canvas>
				
		<u-overlay :show="showCanvas" :duration="400" :z-index ="999" >
				<view class="flex flex-direction justify-end align-center" style="height: 100%;" @touchmove.stop.prevent="stopRoll">
					<view class="canvasItem">
						<image mode="widthFix" style="width:600rpx;height:500rpx" :src="canvasImg"></image>
					</view>
				
					<view class="bg-gray" style="overflow: hidden;margin-top: 50rpx; width: 100%;">
						<view class="flex justify-around margin-tb">
							<label for="buttonShare" class="flex flex-direction align-center justify-center"  @click="showCanvas = false">
								<image src="/static/shareimg/shareImg1.png" mode="" style="width: 60rpx;height: 60rpx;border-radius: 60rpx;"></image>
								<view class="margin-top-sm text-lg">
									分享好友
								</view>
							</label>
							<label for="buttonShare" class="flex flex-direction align-center justify-center"  @click="showCanvas = false">
								<image src="/static/shareimg/shareImg2.png" mode="" style="width: 60rpx;height: 60rpx;border-radius: 60rpx;"></image>
								<view class="margin-top-sm text-lg">
									分享朋友圈
								</view>
							</label>
							<view class="flex flex-direction align-center justify-center" @click="onSaveImg">
								<view class="cu-avatar xl round " style="width: 60rpx;height: 60rpx;background-color: #EA5D5C;">
									<text class="text-white cuIcon-down" style="font-size: 25px;font-weight: bold;"></text>
								</view>
								<view class="margin-top-sm text-lg">
									保存图片
								</view>
							</view>
						</view>
						<view  @click="showCanvas = false;chioceCloseShare()" class="text-bold text-black text-lg text-center bg-white" style="line-height:100rpx;">
							取消
						</view>
					</view>
				</view>
		</u-overlay>
		
       <button id="buttonShare" class="" style="display: none;" open-type="share">	</button>
		
	</view>
</template>

<script>
	import { base64src } from "@/config/base64.js";   // 后面引用路径为base64src.js文件路径
	import _canvas from '@/uni_modules/fan-canvas/canvasUtils';// 加载万能绘制方法
	import { saveImg,qrcodeCanvas } from '@/uni_modules/fan-canvas/plugins/utils';// 需要保存图片和生成二维码可以引用此文件
	export default {
		props: {
			showShore: {
				type: Boolean,
				default: false,
			},
			id:{
				type: [Number,String],
				default: 0,
			},
			decArr:{ //描述
				type:Array,
				default(){
					return ["微信扫码或长按识别二维码","赶快加入我们吧"];
				},
			},
			detail:{
				type:[Object,Array],
				default:()=>{
					return {};
				}
			}
		},
		data() {
			return {
				showCanvas:false, //生成后图片弹框
				canvasImg:'',     //生成的图片
				//小组信息
				// detail:{
				// 	id:0,
				// 	name:"老年大学地方老年大学地方老年大学地方", //小组名称
				// 	image:'https://llkj-wechat.oss-cn-hangzhou.aliyuncs.com/images/20230224/0f184e69a58ef530179a10449da4a454.png',  //小组头像
				// 	back_image:'https://llkj-wechat.oss-cn-hangzhou.aliyuncs.com/images/20230224/0f184e69a58ef530179a10449da4a454.png',
				// 	desc:'搭建交流平台，为老年人提供养老，为老年人提供养为老年人提供养文化娱乐，健康干预和促进等服务，承接政府职能转移、委托以及购买服务等',
				// 	"group_code_url": "",
				// },
			}
		},
		created() {
			
		},
		watch: {
			detail: {
				immediate: true,
				handler(newVal) {
					
				}
			},
			// id:{
			// 	depp:true,   //深度监听
			// 	immediate: true, //首次监听 一打开页面就像监听
			// 	handler(newVal, oldVal) {
			// 		console.log(99999999999999999)
			// 		if(newVal){
			// 			//this.apipostGroupInviteinfo()
			// 		}
			// 	}
			// }
		},
		computed:{			
			//二维码
			erweima(){
				let erweima = ''
				let flag =  this.noEmpty(this.detail)
				if(flag){ //有数据
					let newVal = this.detail;
					erweima = newVal.group_code_url
				}
				return erweima;
			},
		},
		mounted() {
		},
		onReady() {
			
			//二维码
			//this.createGoodsPoster()
		},
		methods:{
			stopRoll(){
				
			},
			//绘制海报
			async createGoodsPoster() {
				  var that = this;
				  let detail = this.detail
				  if(!this.noEmpty(detail)){
					  return;
				  }
			 	uni.showLoading({
			 		title: '海报生成中'
			 	});
			     const cvsW = 600;
			 	 const cvsH = 840;
			     const goodsH = 324;
				 const logo_daxue_w = 86
				 const logo_daxue_h = 104
			 	 const logo_w = 72;
			     const marginLeft = 50;
				
			 	let family = " 'PingFang SC',tahoma,arial,'helvetica neue','hiragino sans gb','microsoft yahei',sans-serif";
			 	let ctx = uni.createCanvasContext('firstCanvas',this);
				
			     // 绘制矩形 背景色
			 	_canvas.fillRoundRect(ctx,0,0,cvsW,cvsH,20,"#EFEFEF");
		
				try{
					 let logoTop = 20; //
					// 绘制圆形头像
					let userAvatar =  that.detail.image  //获取用户头像 
					if(userAvatar){
						userAvatar = userAvatar.replace('http://', 'https://')
						userAvatar = userAvatar.replace('https://thirdwx.qlogo.cn', 'https://wx.qlogo.cn')
						let avatarInfo =  await this.getImageInfoApi(userAvatar);
						_canvas.drawCircular(ctx, avatarInfo.path,marginLeft, logoTop, logo_w, logo_w);
					}
					
				    // 小组昵称					
					let optionsName = {
						font:"bold 36px"+family,     //设置字体
						ctx:ctx,
						word:that.detail.name,      //文本
						maxWidth:cvsW-logo_w-marginLeft-40,  //最大宽度
						maxLine:1,              //最大行数--超出省略
						x:logo_w+marginLeft+20,                   //x坐标
						y:logoTop,                   //y坐标
						l_h: (logo_w/2) + 12,                 //行高
						textCenter:false,       //是否居中显示
						cvsW:cvsW,              //画布总宽--用于计算文字居中
					}
					ctx.setFillStyle('#000000') // 文字颜色
					_canvas.dealWords(optionsName)
					
					// 绘制矩形 背景白色
					_canvas.fillRoundRect(ctx,20,logo_w + logoTop + 20 ,cvsW-40,cvsH-320,20,"#fff");
									
					//高度
					logoTop = logoTop+logo_w + 20
					
					// 同步加载图片
					if(that.detail.back_image){
						let shopimg = await this.getImageInfoApi(that.detail.back_image);
						 _canvas.drawImgCover(ctx, shopimg, marginLeft, logoTop + 30, cvsW-100, goodsH);   // 绘制商品图片
						 ctx.save();  // save+clip+restore:防止图片超出边框显示--相当于overflow: hidden;
						 ctx.clip(); //剪切--不允许超出矩形框
						 ctx.restore();
					}
					
					logoTop = goodsH + 40 + logoTop
					// 简介-多行文字
					ctx.setFillStyle('#010101')
					ctx.textAlign = 'left';
					var options = {
						font:"bold 28px"+family,     //设置字体
						ctx:ctx,
						word: that.detail.desc,      //文本
						maxWidth:cvsW-100,                //最大宽度
						maxLine:3,                   //最大行数--超出省略
						x:marginLeft,   //x坐标
						y:logoTop,                  //y坐标
						l_h:40                  //行高
					}
					_canvas.dealWords(options)  // 文本自定义换行
					

					//高度
					 logoTop = cvsH - 175
			        // 绘制二维码
					 if(that.erweima){
						base64src(that.erweima, (url) => {
							ctx.drawImage(url, marginLeft, logoTop, 140, 140);
						})
					 }
			     
					 //长按图片扫描二维码加入学习
					  ctx.setFillStyle('#000000')
					 ctx.font = '28px' + family
					 ctx.fillText(that.decArr[0], 140+marginLeft+30, logoTop+50)
					 ctx.font = '28px ' + family
					 ctx.fillText(that.decArr[1], 140+marginLeft+30, logoTop+50+42)
			         //绘制图片
			 		ctx.draw(false, function() {
			 			uni.canvasToTempFilePath({
			 				width: cvsW,
			 				height: cvsH,
			 				canvasId: 'firstCanvas',
			 				success(res) {
			 					uni.hideLoading();
			 					that.canvasImg = res.tempFilePath
								that.showCanvas = true;  //弹框
								that.$emit('showScrollTop')
								
								console.log("---------res.tempFilePath",res.tempFilePath)
			 				}
			 			},that)
			 		}, 500)
				}catch(e){
					console.log("海报制作失败",e)
					uni.hideLoading();
					// uni.showToast({
					// 	title: '海报制作失败',
					// 	icon: 'none'
					// });
					that.canvasImg = ''
					return;
				}
			 },
			// 创建二维码
			createQrcode(){
			    var that = this
				//安卓不能生成二维码  自定义组件不能生成
			    qrcodeCanvas('qrcode', 'https://www.baidu.com', 600, 600);
			    const ctx = uni.createCanvasContext('qrcode',this);
				console.log('--111111111------------------',ctx)
			    ctx.draw(true, function() {
			        uni.canvasToTempFilePath({
			            width: 600,
			            height: 600,
			            canvasId: 'qrcode',
			            success(res) {
							console.log('--------------------',res)
							//alert(JSON.stringify(res))
			                // 二维码本地图
			                that.qrcodeImg = res.tempFilePath
			                console.log('createQrcodecreateQrcode',res,'createQrcode')
			            }
			        },that)
			    })
			},
			
			// 保存图片
			async onSaveImg() {
				let imgUrl = "";
				if(this.canvasImg){
					//console.log(this.canvasImg)
					imgUrl = await this.canvasImg;
			        saveImg(imgUrl,()=>{
						this.showCanvas  = false  //关闭弹框
						this.chioceCloseShare()
					})
				}
			},
			//关闭
			chioceCloseShare(){
				this.$emit('close')
			},
			//获取图片信息
			getImageInfoApi(url) {
				return new Promise((resolve,reject) => {
					uni.getImageInfo({
						src: url,
						success: res => {
							resolve(res);
							//resolve(res.path);
						},
						fail: err => {
							reject(err);
							console.log(err);
							// uni.showToast({
							// 	title: '网络错误请重试',
							// 	icon: 'loading'
							// });
						}
					});
				});
			},
			//获取图片信息
			downloadFileApi(url) {
				return new Promise((resolve,reject) => {
					uni.downloadFile({
						//生成临时地址
						url: url,
						success: res => {
							//resolve(res.tempFilePath);
							res.path = res.tempFilePath
							resolve(res);
						},
						fail: err => {
							reject(err);
							console.log(err);
							// uni.showToast({
							// 	title: '网络错误请重试',
							// 	icon: 'loading'
							// });
						}
					});
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	
	/* 按钮去掉边框 */
	button::after {
	  border: none;
	}
	
	.f__canvas {
		width: 300rpx;
		height: 300rpx;
		position: fixed;
		top: -10000rpx;
		left: 0rpx;
	}
	
	.canvasBox{
	    .canvasItem {
			// background-color: red;
	        /* #ifndef APP-NVUE */
	        display: flex;
	        /* #endif */
	        justify-content: center;
	        .img {
	            width: 100%;
	        }
	    }
	    .button {
	        width: 300rpx;
	        height: 80rpx;
	        background: #FF4E16;
	        line-height: 80rpx;
	        text-align: center;
	        font-size: 28rpx;
	        border-radius: 40rpx;
	        margin: 0 auto;
	        margin-top: 20rpx;
			color: #fff;
	    }
	}
</style>
